const express = require('express');
const router = express.Router();
const mysql = require('mysql')
const db = require('../../sql/db')
const $sql = require('../../sql/sqlMap')
const nodemailer = require("nodemailer");

const connection = mysql.createConnection(db.mysql)
connection.connect()
// 登录验证语句
const sql = $sql.user.backPassword;
let VerificationCode;
// 定义邮件服务器服
const transporter = nodemailer.createTransport({
    host: 'smtp.qq.com',
    service: 'qq',
    secure: true,
    // SMTP和POP3服务器的密码
    auth: {
        user: '1317985450@qq.com',
        pass: 'xggeiwroxwasjdjb'
    }
});

router.post('/send', function (req, res, next) {
    // 获取前端传递过来的参数
    console.log(req.body+'s')
    do
        VerificationCode = Math.floor(Math.random()*10000);
    while( VerificationCode < 1000 )

    var sendHtml = `<div>
      <div>验证码 : ${VerificationCode}（五分钟内有效,打死也不要告诉别人哟）</div>
    </div>`;

    var mailOptions = {
        // 发送邮件的地址
        from: '1317985450@qq.com', // login user must equal to this user
        // 接收邮件的地址
        to: req.body.email,  //。
        // 邮件主题
        subject: '区块链学院学分系统验证码',
        // 以HTML的格式显示，这样可以显示图片、链接、字体颜色等信息
        html: sendHtml
    };
    // 发送邮件，并有回调函数
    transporter.sendMail(mailOptions, function (error, info) {
        if (error) {
            return console.log(error);
        }
        console.log('Message sent: ' + info.response + ' 验证码'+VerificationCode);
    });
    res.status(200).json({message: '验证码'+VerificationCode});
});
router.post('/', function (req, res, next) {
    let email = req.body.email;
    let storeId = req.body.storeId;
    console.log(req.body)
    console.log(VerificationCode)
    if(storeId != VerificationCode) {
        res.json({
            status: '1',
            msg: '验证码不正确',
        });
        return
    }
    connection.query(sql, [email,req.body.password], (err, result) => {
        if (err) {
            console.log(err)
            return
        }

        res.json({
            status: '0',
            msg: '找回密码成功',
            result: result
        });
    })
});

module.exports = router;
